package samples.d3.image 
{
	import com.bit101.components.CheckBox;
	import com.bit101.components.HUISlider;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.geom.Matrix;
	import samples.BaseSample;
	
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Sampling extends BaseSample
	{
		
		[Embed(source='../../../../lib/lemur.jpg')]private var imageSrc:Class;
		private var trame:BitmapData;
		private var tmp:BitmapData;
		private var bd:BitmapData;
		private var bmp:Bitmap;
		
		private var scale:Number = 1;
		private var sliderScale:HUISlider;
		
		private var image:Bitmap;
		
		public function Sampling() 
		{
			
			image = new imageSrc();
			image.alpha = .75;
			addChild( image );
			
			trame = new BitmapData( image.width, image.height, true, 0 );
			addChild( new Bitmap( trame ) );
			
			
			tmp = image.bitmapData.clone();
			bd = image.bitmapData.clone();
			bmp = new Bitmap( bd );
			addChild( bmp );
			bmp.x = image.width + 10;
			
			sliderScale = new HUISlider( this, bmp.x, bmp.y - 32, 'scale', changeHandler );
			sliderScale.value = 5;
			
			changeHandler( null );
			center();
			
		}
		
		private function changeHandler( e:Event ):void
		{
			
			
			if ( sliderScale.value < 1 ) sliderScale.value = 1;
			scale = sliderScale.value / 100;
			
			tmp.fillRect( bd.rect, 0 );
			tmp.draw( image, new Matrix( scale, 0, 0, scale ) );
			bd.fillRect( bd.rect, 0 );
			bd.draw( tmp, new Matrix( 1/scale, 0, 0, 1/scale ) );
			
			
			if ( scale >= .5 )
			{
				trame.fillRect( trame.rect, 0xFFFF0000 );
				return;
			}
			
			trame.fillRect( trame.rect, 0 );
			
			var i:int, j:int, step:Number = ( 1 / scale );
			for ( i = 0; i < bd.width; i+=step )
			{
				for ( j = 0; j < bd.height; j+=step )
				{
					trame.setPixel32( i-1, j, 0xFFFF0000 );
					trame.setPixel32( i+1, j, 0xFFFF0000 );
					trame.setPixel32( i, j, 0xFFFF0000 );
					trame.setPixel32( i, j-1, 0xFFFF0000 );
					trame.setPixel32( i, j+1, 0xFFFF0000 );
				}
			}
			
			
		}
		
	}

}